package main

import (
	"encoding/json"
	"fmt"
	"gogs_webhook/src/stl_utils/stl_http_ext"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

type RobotMessageText struct {
	Content             string   `json:"content"`
	MentionedList       []string `json:"mentioned_list,omitempty"`
	MentionedMobileList []string `json:"mentioned_mobile_list,omitempty"`
}

type RobotMessage struct {
	MsgType string           `json:"msgtype"`
	Text    RobotMessageText `json:"text"`
}

type GogsCommitter struct {
	Name     string `json:"name"`
	Email    string `json:"email"`
	Username string `json:"username"`
}

type GogsCommit struct {
	ID        string        `json:"id"`
	Message   string        `json:"message"`
	Url       string        `json:"url"`
	Timestamp string        `json:"timestamp"`
	Committer GogsCommitter `json:"committer"`
	Added     []string      `json:"added"`
	Removed   []string      `json:"removed"`
	Modified  []string      `json:"modified"`
}

type GogsRepository struct {
	Name        string `json:"name"`
	FullName    string `json:"full_name"`
	Description string `json:"description"`
	HtmlUrl     string `json:"html_url"`
}

type GogsInfo struct {
	Ref        string         `json:"ref"`
	Commits    []GogsCommit   `json:"commits"`
	Repository GogsRepository `json:"repository"`
}

func genGogsNotify(info *GogsInfo) string {
	message := ""
	message = message + "仓库" + info.Repository.FullName + "[分支:" + info.Ref + "] 发生变化\r\n"
	message = message + "--------------------------------------------------------------------------------"
	for _, commit := range info.Commits {
		message = message + "\r\n"
		message = message + "版本号: " + commit.ID + "\r\n"
		message = message + "信息: " + commit.Message + "\r\n"
		message = message + "详情: " + commit.Url + "\r\n"
		message = message + "时间: " + commit.Timestamp + "\r\n"
		message = message + "作者: " + commit.Committer.Name + "\r\n"
		if len(commit.Added) > 0 {
			message = message + "Added: \r\n"
			for _, filename := range commit.Added {
				message = message + " \t " + filename + "\r\n"
			}
		}
		if len(commit.Removed) > 0 {
			message = message + "Removed: \r\n"
			for _, filename := range commit.Removed {
				message = message + " \t " + filename + "\r\n"
			}

		}
		if len(commit.Modified) > 0 {
			message = message + "Modified: \r\n"
			for _, filename := range commit.Modified {
				message = message + " \t " + filename + "\r\n"
			}
		}
		message = message + "--------------------------------------------------------------------------------"
	}
	return message
}

func main() {
	router := gin.Default()
	router.GET("/ping", func(c *gin.Context) {
		fmt.Println("/ping")
		c.JSON(http.StatusOK, gin.H{
			"message": "pong",
		})
	})
	router.Any("/gogs/hook", func(c *gin.Context) {
		// fmt.Println("/gogs/hook")
		// // contentType := c.Request.Header.get("Content-Type")
		// contentType1 := strings.ToLower(c.ContentType())
		// contentType2 := strings.ToLower("application/json")
		// fmt.Println(contentType1, contentType2)
		if strings.Contains(strings.ToLower(c.ContentType()), strings.ToLower("application/json")) {

			// string_payload := stl_http_ext.ReadRequestBodyToString(c.Request)
			// fmt.Println(string_payload)

			c.JSON(http.StatusOK, gin.H{
				"message": "OK",
			})

			byte_Payload := stl_http_ext.ReadRequestBodyToBytes(c.Request)
			info := GogsInfo{}
			err := json.Unmarshal(byte_Payload, &info)
			if err != nil {
				fmt.Println(err)
				return
			}

			robotUrl := "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6e29109e-4b82-4c10-803b-af73afb75110"
			notify_message := RobotMessage{
				MsgType: "text",
				Text: RobotMessageText{
					Content: genGogsNotify(&info),
				},
			}
			notify_message_byte, err := json.Marshal(notify_message)
			if err != nil {
				fmt.Println(err)
			}
			res, err := http.Post(robotUrl, "application/json", strings.NewReader(string(notify_message_byte)))
			if err != nil {
				fmt.Println(err)
			}
			fmt.Println(stl_http_ext.ReadResponseBodyToString(res))

		} else {
			c.JSON(http.StatusBadRequest, gin.H{
				"ret":      false,
				"err_code": http.StatusBadRequest,
				"err_msg":  "Content-Type only json",
			})
		}

	})
	router.Static("/assets", "./assets")
	router.StaticFS("/more_static", http.Dir("my_file_system"))
	router.StaticFile("/favicon.ico", "./resources/favicon.ico")
	fmt.Println("Hello World!")
	router.Run("0.0.0.0:8049")
	fmt.Println("Hello World!")
}
